﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.IO;
using System.Diagnostics;
using Microsoft.VisualBasic.Devices;
using System.Net.Sockets;


namespace TMFC
{
    public partial class frmLogin : Form
    {
        //DB.DB DBLink = new DB.DB();
        USM.USMFunc USMFunc = new USM.USMFunc();
        DB.DB DBLink = new DB.DB();
        private System.Threading.Mutex appMutex;
        //private Form formLogin;
        public frmLogin()
        {
            InitializeComponent();


            getFabItem();   //add by brent 20111205


            // 取得登入系统 的 PC 的 IP => 判断该批西所归属的厂别、线别及站别!!
            string strIP = "10.12.13.36";

            // 01.取得本机名称
            string strHostName = Dns.GetHostName();

            // 02.取得本机的 IpHostEntry 类别实体
            IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
            //    IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
            // 03.取得 IP 地址
            // 因应Win7用原方式会有问题,改以下方式get IP by George 991013
            /*baggio
            foreach (IPAddress ip in iphostentry.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    if (ip.ToString().Substring(0, 3) == "192" || ip.ToString().Substring(0, 3) == "10.")
                    {
                        strIP = ip.ToString();
                        break;
                    }
                }
            }
             
       baggio */
            //      strIP = iphostentry.AddressList[0].ToString();

            // 04.取得该 PC 所归属的厂别、线别及站别!!
            DataTable dtTable = new DataTable();

            string strSQL = "select ip.*,fd.dsc_cod1 from fdprcsip ip,fdsyscod_d fd where id_ip = '" + strIP + "'" +
                " and fd.id_cod='IDFAB' and fd.lin_cod=ip.id_fab";
            string stResult = DBLink.executeQuery(strSQL, dtTable);
            if (!stResult.Equals(""))
            {
                MessageBox.Show("取得本电脑的归属厂别、线别及站别资讯时发生异常!! 请与 CIM 人员联络!!");

                dtTable.Dispose();
                dtTable = null;

                GC.Collect();
                this.Close();
            }
            else if (dtTable.Rows.Count != 0)
            {

                Global.gFabID = dtTable.Rows[0]["id_fab"].ToString();
                //lbFab.Text = dtTable.Rows[0]["dsc_cod1"].ToString();  //modify by brent 20111205
                Global.gLineID = dtTable.Rows[0]["id_line"].ToString();
                //lbLine.Text = dtTable.Rows[0]["id_line"].ToString();  //modify by brent 20111205
                Global.gPrcsID = dtTable.Rows[0]["id_prcs"].ToString();
                lbPrcs.Text = dtTable.Rows[0]["id_prcs"].ToString();
                lbNote.Text = dtTable.Rows[0]["note"].ToString();

                //****************************************************************↓
                //add by brent 20111205
                if (dtTable.Rows[0]["id_change"].ToString().Trim().Equals("Y"))
                {
                    cmbFab.Enabled = true;
                    cmbPLine.Enabled = true;
                    cmbFab.Text = "捷扬科技";
                    cmbPLine.Text = "#1";
                }
                else
                {
                    cmbFab.Enabled = false;
                    cmbPLine.Enabled = false;
                }

                getDefFab(Global.gFabID);  //add by brent 20111205
                getDefLine(Global.gLineID);  //add by brent 20111205
                getDefArea();  //add by owen at 20121205

                //****************************************************************↑
            }
            else
            {
                MessageBox.Show("查询归属厂别、线别及站别资讯时发生异常!" + "\r\n" + strSQL);
                GC.Collect();
                this.Close();

            }
            dtTable.Dispose();
            dtTable = null;

            Global.gBprinter = getBINPrinter(Global.gFabID.Trim(), strIP).Trim();   //add by brent 20111020
            Global.gRCprinter = getRCPrinter(Global.gFabID.Trim(), strIP).Trim();  //add by brent 20111020
        }

        private void getDefArea()
        {
            //确定正式区还是测试区
            // 2015/04/16 shiping
            if (DBLink.Connecttype.Equals("TEST") || DBLink.dbConn.DataSource.ToString().Equals("mestest"))
            {
                lbNote2.Text = "测试区";
            }
            else
            {
                lbNote2.Text = "正式区";
            }
            //lbNote2.Text = "";
        }


        private string getBINPrinter(string strFab, string strIP) //add by brent 20111020   取得Bin打印机
        {
            string strReturn = "";

            DBLink = new DB.DB();
            DataTable dtTable = new DataTable();
            string strResult = DBLink.executeQuery("select dsc_cod2 from fdsyscod_d where id_cod = 'BINPRINTER' and sts_data = 'R' and dsc_cod3 = '" + strFab + "' and dsc_cod1 = '" + strIP.Trim() + "'", dtTable);
            if (!strResult.Equals(""))
            {
                //MessageBox.Show("查询时发生异常!");
                strReturn = "";
            }
            else
            {
                if (dtTable.Rows.Count > 0)
                    strReturn = dtTable.Rows[0][0].ToString();
            }


            dtTable.Dispose();
            dtTable = null;

            return strReturn;
        }

        private string getRCPrinter(string strFab, string strIP) //add by brent 20111020   取得R/C打印机
        {
            string strReturn = "";

            DBLink = new DB.DB();
            DataTable dtTable = new DataTable();
            string strResult = DBLink.executeQuery("select dsc_cod2 from fdsyscod_d where id_cod = 'RCPRINTER' and sts_data = 'R' and dsc_cod3 = '" + strFab + "' and dsc_cod1 = '" + strIP.Trim() + "'", dtTable);
            if (!strResult.Equals(""))
            {
                //MessageBox.Show("查询时发生异常!");
                strReturn = "";
            }
            else
            {
                if (dtTable.Rows.Count > 0)
                    strReturn = dtTable.Rows[0][0].ToString();
            }

            dtTable.Dispose();
            dtTable = null;

            return strReturn;
        }


        private void btnOK_Click(object sender, EventArgs e)
        {

            //string strSQL = "Select * from fduser where id_usr='" + txtIDUsr.Text.Trim() + "'" +
            //    " and pwd_usr='" + txtPwdUsr.Text.Trim() + "'";
            //bool log = DBLink.executeQuery(strSQL);

            bool log = USM.USMFunc.chkIDPassword(txtIDUsr.Text.Trim(), txtPwdUsr.Text.Trim());
            if (!log)
            {
                MessageBox.Show("用户账号/密码错误,无法登入!");
                return;
            }
            bool log1 = USM.USMFunc.chkIDDate(txtIDUsr.Text.Trim(), txtPwdUsr.Text.Trim());
            if (!log1)
            {
                MessageBox.Show("密码已失效,请修改密码!");
                txtID.Text = txtIDUsr.Text;
                this.Width = Width + 250;
                groupBox1.Visible = true;
                return;
            }

            // 关闭登入视窗
            this.Hide();

            frmMainMenu Main = new frmMainMenu(txtIDUsr.Text.Trim());
            Main.ShowDialog();

            GC.Collect();
            this.Close();

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            GC.Collect();
            this.Close();
        }

        private void txtIDUsr_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
                txtPwdUsr.Focus();
        }

        private void txtPwdUsr_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
                btnOK_Click(null, null);
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            //skinEngine1.SkinFile = Application.StartupPath + @"\MacOS.ssk";  //换皮肤
            string str = System.Windows.Forms.Application.StartupPath;          //Z:\Release   //D:\TMFC
            if (str.Length > 7)
                if (!str.Substring(0, 7).Equals("D:\\TMFC"))
                {
                    if (str.Substring(0, 10).Equals("Z:\\Release"))
                    {
                        MessageBox.Show("MES不允许直接从【Z:\\Release】中打开，系统已停止！\n 请使用本机安装的MES!", "错 误 警 告！");

                        this.Close();
                        this.Dispose();
                        GC.Collect();
                    }
                }
            string startpath = Application.StartupPath;
            StreamReader verStr = new StreamReader(@startpath + "\\Config.ini");
            this.Text = this.Text + " @版本:" + verStr.ReadLine();


            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
            bool createNew;
            appMutex = new System.Threading.Mutex(true, "TMFC", out createNew);
            if (!createNew)
            {
                appMutex.Close();
                appMutex = null;
                Close();
                return;
            }
        }

        private void Application_ApplicationExit(object sender, EventArgs e)
        {
            if (appMutex != null)
            {
                appMutex.ReleaseMutex();
                appMutex.Close();
            }
        }



        private void getFabItem()   //add by brent 20111205
        {
            DataTable dtTable;
            dtTable = new DataTable();
            int i = 0;
            string strResult = "";
            cmbFab.Items.Clear();
            if (strResult != "")
            {
                MessageBox.Show("查询厂别ComboBoxItem时发生异常！");
                return;
            }
            else
                for (i = 0; i <= dtTable.Rows.Count - 1; i++)
                {
                    cmbFab.Items.Add(dtTable.Rows[i][0].ToString());
                }

            if (cmbFab.Items.Count > 0)
                cmbFab.SelectedIndex = 0;
            dtTable.Dispose();
            dtTable = null;
        }

        private void cmbFab_SelectedIndexChanged(object sender, EventArgs e)    //add by brent 20111205
        {
            if (cmbFab.Text.Trim() != "")
                getProdLine(cmbFab.Text.Substring(0, cmbFab.Text.IndexOf("(")), cmbPLine);

            Global.gFabID = cmbFab.Text.Trim().Substring(0, cmbFab.Text.Trim().IndexOf("("));
            Global.gLineID = cmbPLine.Text.Trim().Substring(0, cmbPLine.Text.Trim().IndexOf(":"));



        }

        private void getProdLine(string nFab, ComboBox nPLine)  //add by brent 20111205
        {
            nPLine.Text = "";
            nPLine.Items.Clear();

            DataTable dtTable = new DataTable();
            string stResult = DBLink.executeQuery("Select lin_cod||':'||dsc_cod1 from fdsyscod_d where id_cod='IDLINE'" +
                " and sts_data='R'" +
                 " and dsc_cod3='" + nFab + "'" +
                " order by lin_cod", dtTable);
            if (!stResult.Equals(""))
            {
                MessageBox.Show("查询生产线别设定时发生异常!");
            }
            else
            {
                for (int i = 0; i <= dtTable.Rows.Count - 1; i++)
                    nPLine.Items.Add(dtTable.Rows[i][0].ToString());
            }

            nPLine.SelectedIndex = 0;

            dtTable.Dispose();
            dtTable = null;
        }


        private void getDefFab(string nFab) //由传入的值、代入预设厂别
        {
            //厂别
            for (int i = 0; i <= cmbFab.Items.Count - 1; i++)
            {
                if (cmbFab.Items[i].ToString().Trim().Substring(0, cmbFab.Items[i].ToString().Trim().IndexOf("(")).Equals(nFab))
                {
                    cmbFab.SelectedIndex = i;
                }
            }

        }

        private void getDefLine(string nPLine) //由传入的值、代入预设线别
        {
            //线别
            for (int i = 0; i <= cmbPLine.Items.Count - 1; i++)
            {
                if (cmbPLine.Items[i].ToString().Trim().Substring(0, cmbPLine.Items[i].ToString().Trim().IndexOf(":")).Equals(nPLine))
                {
                    cmbPLine.SelectedIndex = i;
                }
            }

        }

        private void txtPwdUsr_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnChangepwd_Click(object sender, EventArgs e)
        {
            this.Width = Width + 250;
            groupBox1.Visible = true;
            if (!txtIDUsr.Text.Equals(""))
            {
                txtID.Text = txtIDUsr.Text;
            }
        }

        private void btnchangeok_Click(object sender, EventArgs e)
        {
            if (txtOldPwd.Text.Equals(""))
            {
                MessageBox.Show(this, "请输入原密码!!", "变更密码错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (txtNewPwd.Text.Equals(""))
            {
                MessageBox.Show(this, "请输入新密码!!", "变更密码错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (txtNewPwd2.Text.Equals(""))
            {
                MessageBox.Show(this, "请再次确认新密码!!", "变更密码错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (txtOldPwd.Text.Equals(txtNewPwd.Text))
            {
                MessageBox.Show(this, "新密码与原密码不可相同,请重新输入", "变更密码错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtNewPwd.SelectAll();
                return;
            }
            else if (!txtNewPwd2.Text.Equals(txtNewPwd.Text))
            {
                MessageBox.Show(this, "新密码确认错误!!请再次确认新密码", "变更密码错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtNewPwd.SelectAll();
                return;
            }
            else
            {
                DataTable dtTable = new DataTable();
                bool ins = USM.USMFunc.chkIDPassword(txtID.Text, txtOldPwd.Text);
                if (!ins)
                {
                    MessageBox.Show(this, "原密码输入错误!!请重新输入!!", "变更密码失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtOldPwd.Text = "";
                    txtNewPwd.Text = "";
                    txtNewPwd2.Text = "";

                    txtOldPwd.Focus();
                    return;
                }
                else
                {
                    // 释放 dtTable 资源
                    dtTable.Dispose();
                    dtTable = null;

                    // 更新新的密码
                    string strSQL = "update fduser set pwd_usr = '" + txtNewPwd.Text + "',dat_trn='" + DateTime.Now.ToString("yyyy/MM/dd") + "',tim_trn='" + DateTime.Now.ToString("HH:mm:ss") + "' where id_usr = '" + txtID.Text + "'";
                    string strResult = DBLink.executeTrx(strSQL);
                    if (strResult.Equals(""))
                    {
                        MessageBox.Show(this, "变更密码成功!!下次请以新密码登入!!", "变更密码成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 关闭登入窗口
                        this.Hide();

                        frmMainMenu Main = new frmMainMenu(txtIDUsr.Text.Trim());
                        Main.ShowDialog();

                        GC.Collect();
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show(this, "变更密码失败!!请与 CIM 人员联络!!", "变更密码失败!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtOldPwd.Text = "";
                        txtNewPwd.Text = "";
                        txtNewPwd2.Text = "";

                        txtOldPwd.Focus();
                    }
                }
            }
            groupBox1.Visible = false;
            //this.ShowDialog();
        }



    }
}
